package top.igotcha.article.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.igotcha.article.dao.ArticleDao;
import top.igotcha.article.pojo.Article;
import top.igotcha.util.IdWorker;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Gotcha
 * @date 2021/1/28
 * @describe
 */
@Service
public class ArticleService {

    @Autowired
    private ArticleDao articleDao;
    @Autowired
    private IdWorker idWorker;

    public List<Article> findAll(){
        return articleDao.selectList(null);
    }
    public Article findById(String id) {
        return articleDao.selectById(id);
    }

    /**
     * @param article 文章实体
     * @describe 新添加文章时，主键由分布式ID生成器生成，将访问数，点赞数，评论数置为零
     */
    public void add(Article article) {
        //初始化设置
        article.setId(idWorker.nextId() + "");
        article.setVisits(0);
        article.setThumbup(0);
        article.setComment(0);
        articleDao.insert(article);
    }

    public void update(Article article) {
        //方法1，根据id号更新
        articleDao.updateById(article);

        //方法2，根据条件更新
        //EntityWrapper wrapper = new EntityWrapper<Article>();
        //wrapper.eq("id", article.getId());
        //articleDao.update(article, wrapper);
    }
    public void delete(String id) {
        articleDao.deleteById(id);
    }

    public Page<Article> search(Map map, int page, int size) {
        EntityWrapper<Article> wrapper = new EntityWrapper<>();
        Set<String> fieldSet = map.keySet();
        //设置查询条件
        for(String field : fieldSet) {
            //根据条件动态拼接SQL
            wrapper.eq(null != map.get(field), field, map.get(field));
        }
        //设置分页参数
        Page<Article> pageData = new Page<>(page, size);
        //查询
        List<Article> list = articleDao.selectPage(pageData, wrapper);
        pageData.setRecords(list);
        return pageData;
    }
}
